package org.nanotek.dao;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.nanotek.util.Base;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

public abstract class BaseDAO {

	protected Class<Base<?>> clazz;  
	@Autowired
	private SessionFactory sessionFactory; 
	
	
	public BaseDAO() {
	}

	public BaseDAO(Class<Base<?>> clazz) {
		this.clazz = clazz;
	}
	
	@Transactional (readOnly = true, propagation = Propagation.REQUIRED)
	public List<Base<?>> loadAll() {
		Session session = sessionFactory.getCurrentSession();
		return session.createQuery("from " + getClazz().getName()).list();
	}

	@Transactional (readOnly = false, propagation = Propagation.REQUIRED)
	public void persist(Base<?> object) {
		Session session = sessionFactory.getCurrentSession();
		session.persist(object);
	}

	@Transactional (readOnly = false, propagation = Propagation.REQUIRED)
	public void update(Base<?> object) {
		Session session = sessionFactory.getCurrentSession();
		session.saveOrUpdate(object);
	}

	@Transactional (readOnly = false, propagation = Propagation.REQUIRED)
	public void delete(Base<?> object) {
		Session session = sessionFactory.getCurrentSession();
		session.delete(object);
	}

	public Class<Base<?>> getClazz() {
		return clazz;
	}

	public void setClazz(Class<Base<?>> clazz) {
		this.clazz = clazz;
	}
	
	@Transactional
	public abstract List<Base<?>> listRecords(Integer firstResult, Integer maxResults);

	public SessionFactory getSessionFactory() {
		return sessionFactory;
	}

	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}

}
